<?php
/**
 * Created by PhpStorm.
 * User: tangchao
 * Date: 19-4-20
 * Time: 下午4:20
 */

namespace Lib;

use Lib\Db\MySQLi;

/**
 * 迭代器模式获取数据对象
 * Class AllUser
 * @package Lib
 */
class AllUser implements \Iterator
{
    protected $index;
    protected $data = [];
    protected $ids;

    public function __construct()
    {
        $db = new MySQLi();
        $db->connect('127.0.0.1','root','st826115','es_pool');
        $res = $db->query("select id from user");
        //MYSQLI_ASSOC Columns are returned into the array having the fieldname as the array index.
        $this->ids = $res->fetch_all(MYSQLI_ASSOC);
    }

    //初始化索引
    public function rewind()
    {
        $this->index = 0;
    }

    //验证是否还有下一个元素
    public function valid()
    {
        return $this->index < count($this->ids);
    }

    //获取当前元素
    public function current()
    {
        $id = $this->ids[$this->index]['id'];
        return Factory::getUser($id);
    }

    //下一个元素
    public function next()
    {
        $this->index ++;
    }

    //获取当前位置
    public function key()
    {
        return $this->index;
    }
}